package com.shj.em.generator;

import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DbType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.AbstractTemplateEngine;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Data
public class MyGenerator extends AutoGenerator {

    protected static final Logger logger = LoggerFactory.getLogger(MyGenerator.class);

    //修改替换成你需要的表名，多个表名传数组
    protected String[] tableNames;

    protected String DB_URL = "jdbc:mysql://localhost:3306/baseem?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&useSSL=false";
    protected String DB_USERNAME = "root";
    protected String DB_PASSWORD = "123456";
    protected String DB_DRIVER = "com.mysql.jdbc.Driver";

    protected String PACKAGE_NAME = "com.shj.em.biz";
    protected String MODULE_NAME = "sys";//模块名称
    protected String PROJECT_PATH = "E:/project/em/mingren/mingren";
    protected boolean FILE_OVERRIDE = false;//文件是否覆盖，false不覆盖

    protected String tablePrefix="sys_";
    protected String SUPER_ENTITY_CLASS = "com.shj.em.base.entity.BaseEntity";
    //protected String SUPER_CONTROLLER_CLASS = "com.shj.em.base.controller";

    protected String entity = "/templates/my.entity.java";
    protected String service = "/templates/my.service.java";
    protected String serviceImpl = "/templates/my.serviceImpl.java";
    protected String mapper = "/templates/my.mapper.java";
    protected String xml = "/templates/my.mapper.xml";
    protected String controller = "/templates/my.controller.java";


    private TemplateConfig templateCfg = new TemplateConfig();
    private GlobalConfig globalCfg = new GlobalConfig(); //全局配置
    private DataSourceConfig dataSourceConfig = new DataSourceConfig();
    private StrategyConfig strategyConfig = new StrategyConfig();
    private PackageConfig packageCfg;

    private AbstractTemplateEngine engine = new MyTemplateEngine();

    public void generateCode() {

        initConfig(tableNames);

        this.setGlobalConfig(globalCfg)
                .setDataSource(dataSourceConfig)
                .setStrategy(strategyConfig)
                .setPackageInfo(packageCfg)
                .setCfg(injectionConfig)
                .setTemplate(templateCfg);

        this.setTemplateEngine(engine);

        // 生成后端代码
        this.execute();
    }

    private void addOtherGeneratedFiles(List<FileOutConfig> focList){
        final String htmlFolder = PROJECT_PATH + "/src/main/resources/templates/" + MODULE_NAME;
        final String jsFolder = PROJECT_PATH + "/src/main/resources/static/js/appjs/" + MODULE_NAME;

        // search.js
        focList.add(new FileOutConfig("/templates/search.js.ftl") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return jsFolder + "/" + tableInfo.getEntityName().toLowerCase() +".js";
            }
        });

        //search.html
        focList.add(new FileOutConfig("/templates/search.html.ftl") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return htmlFolder + "/" + tableInfo.getEntityName().toLowerCase() + "/search.html";
            }
        });

        //add.html
        focList.add(new FileOutConfig("/templates/add.html.ftl") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return htmlFolder + "/" + tableInfo.getEntityName().toLowerCase() + "/add.html";
            }
        });

        //view.html
        focList.add(new FileOutConfig("/templates/view.html.ftl") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return htmlFolder + "/" + tableInfo.getEntityName().toLowerCase() + "/view.html";
            }
        });
    }


    public void initConfig(String ... tables){
        if (tables ==null || tables.length == 0) {
            return;
        }

        File file = new File(PROJECT_PATH + "/src/main/java");

        //1. 全局配置
        globalCfg.setActiveRecord(false)
                .setAuthor("Shen Huang Jian")
                .setOutputDir(file.getAbsolutePath())
                .setEnableCache(false)
                .setFileOverride(FILE_OVERRIDE)//关闭文件覆盖
                .setOpen(false) //关闭打开
                .setServiceName("%sService")
                .setBaseResultMap(true)
                .setEnableCache(false);

        //1.1 数据源配置
        dataSourceConfig.setDbType(DbType.MYSQL)
                .setUrl(DB_URL)
                .setUsername(DB_USERNAME)
                .setPassword(DB_PASSWORD)
                .setDriverName(DB_DRIVER);

        //1.2 生成策略配置
        strategyConfig.setTablePrefix(tablePrefix)
                .setCapitalMode(true)
                .setEntityLombokModel(true)
                .setDbColumnUnderline(true)
                .setNaming(NamingStrategy.underline_to_camel)
                .setSuperEntityClass(SUPER_ENTITY_CLASS)
                .setSuperEntityColumns(DataConstant.DEFAULT_AUDIT_TABLE_FIELDS_NAME)
                .setLogicDeleteFieldName("del_flag")
                .setVersionFieldName("version")
                .setInclude(tableNames);
//                .setSuperControllerClass();

        // 模板配置
        templateCfg.setController(controller);
        templateCfg.setService(service);
        templateCfg.setServiceImpl(serviceImpl);
        templateCfg.setMapper(mapper);
        templateCfg.setEntity(entity);
        templateCfg.setXml(null);

        //
        packageCfg = new PackageConfig()
                .setParent(PACKAGE_NAME)
                .setController("controller")
                .setEntity("entity").setService("service")
                .setServiceImpl("service")
                .setModuleName(MODULE_NAME);

        // 自定义模板时，需要的定义的参数
        injectionConfig = new InjectionConfig(){
            @Override
            public void initMap() {
                Map<String, Object> hashMap = getParameterMap();
                this.setMap(hashMap);
            }
        };

        List<FileOutConfig> focList = new ArrayList();

        // 调整 xml 生成目录演示
        focList.add(new FileOutConfig(this.xml.concat(".ftl")) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return PROJECT_PATH + "/src/main/resources/mapper/"+MODULE_NAME+"/"+ tableInfo.getEntityName() + "Mapper.xml";
            }
        });

        addOtherGeneratedFiles(focList);

        injectionConfig.setFileOutConfigList(focList);
    }

    public Map<String, Object> getParameterMap() {
        Map<String, Object> map = new HashMap<>();
        map.put("module", MODULE_NAME);
        return map;
    }

    public void makeDirs(String path){
        File file = new File(path);
        if(!file.exists()){
            file.mkdirs();
        }
    }




}
